package com.trigsoft.utils;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

import com.trigsoft.applist.DBHelper;

public class CatGetter
{
	private static class TrustAnyTrustManager implements X509TrustManager
	{

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
		{
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
		{
		}

		public X509Certificate[] getAcceptedIssuers()
		{
			return new X509Certificate[] {};
		}

	}

	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		//HttpHost targetHost = new HttpHost("market.android.com", 443, "https");
		//getPackage("com.dianpin.v1");
		System.out.println("lskdjf");
	}

	private HashMap<String, String> catMap;
	private final static int CAT_NUM = 32;
	private HttpHost httpHost = new HttpHost("market.android.com");

	private HttpClient client;

	private boolean wifi;

	public CatGetter(Context context)
	{
		catMap = getCatMap();
		wifi = NetworkUtils.isWiFiActive(context);
	}

	public String getCat(String pkg, boolean searchWeb)
	{
		String cat = DBHelper.getCat(pkg);
		if (searchWeb && cat.compareTo("other") == 0 && wifi)
			cat = getPackage(pkg);
		return cat;
	}

	private HashMap<String, String> getCatMap()
	{
		HashMap<String, String> catMap = new HashMap<String, String>(CAT_NUM);
		catMap = new HashMap<String, String>(CAT_NUM);
		catMap.put("CASUAL", "game");
		catMap.put("SPORTS_GAMES", "game");
		catMap.put("GAME_WALLPAPER", "game");
		catMap.put("RACING", "game");
		catMap.put("ARCADE", "game");
		catMap.put("BRAIN", "game");
		catMap.put("GAME_WIDGETS", "game");
		catMap.put("CARDS", "game");

		catMap.put("PERSONALIZATION", "personalization");
		catMap.put("APP_WALLPAPER", "personalization");

		catMap.put("NEWS_AND_MAGAZINES", "book");
		catMap.put("BOOKS_AND_REFERENCE", "book");
		catMap.put("COMICS", "book");

		catMap.put("BUSINESS", "business");

		catMap.put("EDUCATION", "education");

		catMap.put("FINANCE", "finace");

		catMap.put("LIFESTYLE", "lifestyles");
		catMap.put("PRODUCTIVITY", "lifestyles");
		catMap.put("MEDICAL", "lifestyles");
		catMap.put("WEATHER", "lifestyles");
		catMap.put("HEALTH_AND_FITNESS", "lifestyles");

		catMap.put("ENTERTAINMENT", "entertainments");
		catMap.put("MEDIA_AND_VIDEO", "entertainments");
		catMap.put("MUSIC_AND_AUDIO", "entertainments");

		catMap.put("COMMUNICATION", "communication");
		catMap.put("SOCIAL", "communication");

		catMap.put("PHOTOGRAPHY", "photo");

		catMap.put("SPORTS", "sport");

		catMap.put("TOOLS", "tool");

		catMap.put("TRANSPORTATION", "transportation");
		catMap.put("TRAVEL_AND_LOCAL", "transportation");

		catMap.put("SHOPPING", "shopping");
		return catMap;
	}

	private HttpClient getClient()
	{
		SSLContext sslcontext;
		HttpClient c;
		try
		{
			sslcontext = SSLContext.getInstance("SSL");
			TrustManager easyTrustManager = new TrustAnyTrustManager();
			sslcontext.init(null, new TrustManager[] {easyTrustManager}, null);
			SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();

			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);

			SchemeRegistry schemeRegistry = new SchemeRegistry();

			schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

			ClientConnectionManager cm = new ThreadSafeClientConnManager(new DefaultHttpClient().getParams(),
					schemeRegistry);

			c = new DefaultHttpClient(cm, new DefaultHttpClient().getParams());

			c.getConnectionManager().getSchemeRegistry().register(https);
			return c;
		} catch (NoSuchAlgorithmException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyManagementException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String getPackage(String pkg)
	{
		if (client == null)
			client = getClient();
		try
		{
			HttpGet getRequest = new HttpGet("/details?id=" + pkg);

			HttpResponse response = client.execute(httpHost, getRequest);

			String responseContent = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

			//System.out.print(responseContent);
			//System.out.println();
			//System.out.println();
			String regex = "a href=\"/apps/([a-zA-Z_]+)\"";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(responseContent);

			//Log.d("test", pkg);
			if (m.find())
			{
				Log.d("test", m.group(1) + pkg);
				if (catMap.containsKey(m.group(1)))
					return catMap.get(m.group(1));
				else
					return "other";

			} else
				return "other";

		} catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "other";
	}
}
